<template>
  <el-card class="section-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>新增知识文档</span>
        <el-switch v-model="form.autoEmbed" active-text="自动生成向量" inactive-text="手动上传" />
      </div>
    </template>

    <el-form :model="form" ref="formRef" label-position="top">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请输入标题' }]"><el-input v-model="form.title" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="输入或选择标签"
            >
              <el-option v-for="tag in suggestions" :key="tag" :label="tag" :value="tag" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="内容" prop="content" :rules="[{ required: true, message: '请输入文档内容' }]"><el-input type="textarea" v-model="form.content" :rows="6" /></el-form-item>

      <el-form-item v-if="!form.autoEmbed" label="向量（JSON 数组）">
        <el-input
          type="textarea"
          v-model="form.vectorText"
          :rows="4"
          placeholder="[0.1, 0.2, ...]"
        />
      </el-form-item>

      <el-form-item label="来源">
        <el-input v-model="form.metadata.source" placeholder="如：ElementPlus 文档" />
      </el-form-item>

      <div class="form-actions">
        <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useDocsStore } from '@/stores/docs';

const docsStore = useDocsStore();

const formRef = ref();
const saving = ref(false);
const suggestions = ref(['组件', '案例', 'API', '指南']);

const form = reactive({
  title: '',
  content: '',
  tags: [],
  metadata: { source: '' },
  vectorText: '',
  autoEmbed: true
});

function parseVector(text) {
  if (!text) return null;
  try {
    const parsed = JSON.parse(text);
    if (Array.isArray(parsed)) {
      return parsed.map((value) => Number(value));
    }
  } catch (error) {
    console.error('Failed to parse vector', error);
  }
  return null;
}

function reset() {
  form.title = '';
  form.content = '';
  form.tags = [];
  form.metadata.source = '';
  form.vectorText = '';
  form.autoEmbed = true;
}

async function submit() {
  await formRef.value.validate();
  saving.value = true;
  try {
    const payload = {
      title: form.title,
      content: form.content,
      metadata: {
        tags: form.tags,
        source: form.metadata.source
      },
      autoEmbed: form.autoEmbed
    };
    if (!form.autoEmbed) {
      payload.vector = parseVector(form.vectorText);
    }
    await docsStore.createDoc(payload);
    ElMessage.success('文档已保存');
    reset();
  } catch (error) {
    ElMessage.error(error.message || '保存失败');
  } finally {
    saving.value = false;
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.form-actions {
  display: flex;
  gap: 12px;
}
</style>
